package com.yh.utils;

import org.apache.log4j.Logger;
import sun.misc.BASE64Encoder;

import java.security.MessageDigest;
import java.util.Random;

/**
 * 密码的安全处理
 *
 * @author yuhuan
 * @date 2022/01/13
 */
public class Md5Security {
    /**
     * 日志
     */
    private static final Logger logger = Logger.getLogger(Md5Security.class);

    static String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    /**
     * 使用MD5加密
     */
    public static String pwdToMd5(String password) {
        try {
            // 拿到一个MD5转换器
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            BASE64Encoder base64Encoder = new BASE64Encoder();
            return base64Encoder.encode(md5.digest(password.getBytes("utf-8")));
        } catch (Exception e) {
            logger.error("<<<<< 密码加密失败！");
        }
        return password;
    }

    /**
     * 将密码拼接额外的前缀字符串再使用MD5加密
     */
    public static String makePrefixToMd5(String randomString, String password) {
        return pwdToMd5(password + randomString);
    }

    /**
     * 从"str"指定的字符串中获取随机的字符并拼接成新的字符串，字符串长度由参数length指定
     */
    public static String getRandomString(int length) {
        Random random = new Random();
        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < length; i++) {
            int number = random.nextInt(str.length());
            sb.append(str.charAt(number));
        }

        return sb.toString();
    }


    /**
     * 测试代码
     */
    public static void main(String[] args) {
        // 密码
        String password = "123456";
        // 前缀
        String randomString = getRandomString(10);
        System.out.println("前缀~" + randomString);
        // 加密
        String md5 = makePrefixToMd5(randomString, password);
        System.out.println("加密~" + md5);
    }
}
